<template>
    <div class="main">
        <section>
            <div v-if="rightsButtons['add']" class="btn-block">
                <el-button type="success" size="small" icon="el-icon-circle-plus" plain @click="showAdd">新建活动</el-button>
            </div>
            <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
                <el-table-column align="center" label="活动名称" prop="name"></el-table-column>
                <el-table-column align="center" label="类型" prop="type" width="80">
                    <template slot-scope="scope">
                        <span v-if="scope.row.type===4">打折</span>
                        <span v-if="scope.row.type===5">满减</span>
                        <span v-if="scope.row.type===6">买赠</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="活动开始时间" prop="startTime">
                    <template slot-scope="scope">
                        <span v-text="formatDate(scope.row.startTime, 'yyyy-MM-dd hh:mm:ss')"></span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="活动结束时间" prop="stopTime">
                    <template slot-scope="scope">
                        <span v-text="formatDate(scope.row.stopTime, 'yyyy-MM-dd hh:mm:ss')"></span>
                    </template>
                </el-table-column>
                <!--<el-table-column align="center" label="活动描述" prop="description"></el-table-column>-->
                <el-table-column align="center" label="是否启用" prop="status" width="120">
                    <template slot-scope="scope">
                        {{scope.row.status?'启用':'不启用'}}
                    </template>
                </el-table-column>
                <!--<el-table-column align="center" label="备注" prop="remarks"></el-table-column>-->
                <el-table-column align="center" label="操作" v-if="rightsButtons['edit'] || rightsButtons['goods']">
                    <template slot-scope="scope">
                        <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                        <router-link v-if="rightsButtons['goods']" :to="{name: 'activityActivityGoods', params: {id: scope.row.activityId}, query: {actType: scope.row.type}}">
                            <el-button type="primary" plain size="mini">商品管理</el-button>
                        </router-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="listQuery.pageIndex"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="listQuery.pageSize"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listTotal">
            </el-pagination>
            <el-dialog :title="formData.id ? '编辑活动' : '新建活动'" :visible.sync="showEditPop">
                <el-form :model="formData" :rules="formRule" size="medium" ref="form" label-width="120px">
                    <el-form-item label="活动名称:" prop="name">
                        <el-input v-model="formData.name"></el-input>
                    </el-form-item>
                    <el-form-item label="活动banner:" prop="banner" class="banner-container">
                        <el-upload
                                class="avatar-uploader"
                                :action="upladUrl"
                                name="file"
                                :show-file-list="false"
                                :on-success="uploadSuccess"
                                :before-upload="beforeUpload">
                            <img v-if="formData.banner" :src="formData.banner" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="活动类型:" prop="type">
                        <el-select v-model="formData.type" placeholder="请选择" :disabled="!!formData.id">
                            <el-option :key="4" label="打折" :value="4"></el-option>
                            <el-option :key="5" label="满减" :value="5"></el-option>
                            <el-option :key="6" label="买赠" :value="6"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="折扣:" v-if="formData.type===4" prop="discount">
                        <el-input type="number" v-model="formData.discount">
                            <template slot="append">折</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="满减:" v-if="formData.type===5" prop="full">
                        <el-col :span="11">
                            <el-form-item prop="full">
                                <el-input type="number" v-model="formData.full">
                                    <template slot="prepend">满</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2" class="line">-</el-col>
                        <el-col :span="11">
                            <el-form-item prop="price">
                                <el-input type="number" v-model="formData.price">
                                    <template slot="prepend">减</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="买赠:" v-if="formData.type===6" prop="full">
                        <el-row v-for="(item, index) in formData.tempActName" :key="index">
                            <el-col :span="9">
                                <el-form-item :prop="'tempActName['+index+'].buyNum'">
                                    <el-input type="number" v-model="item.buyNum">
                                        <template slot="prepend">买</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="9">
                                <el-form-item :prop="'tempActName['+index+'].giveNum'">
                                    <el-input type="number" v-model="item.giveNum">
                                        <template slot="prepend">送</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6" style="text-align: right">
                                <el-button v-if="!index" type="success" size="small" icon="el-icon-circle-plus" plain @click="addAct">添加规则</el-button>
                                <el-button v-else type="danger" size="small" icon="el-icon-remove" plain @click="delAct(index)">移除规则</el-button>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item label="活动时间:" prop="timeRange">
                        <el-date-picker
                                v-model="formData.timeRange"
                                type="datetimerange"
                                range-separator="~"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="是否启用:" prop="status">
                        <el-switch
                                v-model="formData.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0">
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="活动描述:" prop="description">
                        <el-input type="textarea" :rows="2" v-model="formData.description"></el-input>
                    </el-form-item>
                    <el-form-item label="备注:" prop="remarks">
                        <el-input type="textarea" :rows="2" v-model="formData.remarks"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="save" :loading="btnLoading">保存</el-button>
                    <el-button @click="showEditPop = false">取消</el-button>
                </div>
            </el-dialog>
        </section>
    </div>
</template>
<script>
    export default {
        name: 'activityList',
        data() {
            return {
                listQuery: {
                    pageIndex: 1,
                    pageSize: 10,
                    isPage: 1
                },
                listLoading: false,
                list: [],
                listTotal: 0,

                showEditPop: false,
                btnLoading: false,
                formData: {
                    name: '',
                    banner: '',
                    type: '',
                    discount: '',
                    full: '',
                    price: '',
                    tempActName: [{
                        buyNum: '',
                        giveNum: ''
                    }],
                    timeRange: [],
                    status: 0,
                    description: '',
                    remarks: ''
                },
                formRule: {
                    name: [{required: true, message: '不能为空', trigger: 'change'}],
                    banner: [{required: true, message: '请上传banner'}],
                    type: [{required: true, message: '请选择', trigger: 'change'}],
                    timeRange: [{required: true, message: '请设置', trigger: 'change'}],
                    description: [{required: true, message: '不能为空', trigger: 'change'}]
                }
            }
        },
        created(){
            this.getList()
        },
        methods: {
            getList(){
                this.listLoading = true;
                this.request({
                    url: '/bsnl-activity/activity/query',
                    //url: '/activity/query',
                    method: 'post',
                    data: this.listQuery
                }).then(({data, totalCount}) => {
                    this.list = data;
                    this.listTotal = totalCount;
                    this.listLoading = false;
                }).catch(err => {
                    console.log(err);
                    this.list = [];
                    this.listTotal = 0;
                    this.listLoading = false;
                });
            },
            handleSizeChange (value) {
                this.listQuery.pageSize = value
                this.getList()
            },
            handleCurrentChange(val){
                this.listQuery.pageIndex = val;
                this.getList();
            },
            beforeUpload(file){
                if (!/image/.test(file.type)) {
                    this.$message.error('只能上传图片');
                    return false;
                }
                if (file.size > 1024 * 1024) {
                    this.$message.error('图片不能大于1M');
                    return false;
                }
            },
            uploadSuccess(res) {
                this.formData.banner = this.replaceImgUrl(res.filePath);
            },
            //新增满赠规则
            addAct(){
                this.formData.tempActName.push({
                    buyNum: '',
                    giveNum: ''
                })
            },
            //移除满赠规则
            delAct(index){
                this.formData.tempActName.splice(index, 1)
            },
            // 新建
            showAdd() {
                this.formData = {
                    name: '',
                    banner: '',
                    type: '',
                    discount: '',
                    full: '',
                    price: '',
                    tempActName: [{
                        buyNum: '',
                        giveNum: ''
                    }],
                    actName: '',
                    timeRange: [],
                    status: 0,
                    description: '',
                    remarks: ''
                };
                this.$nextTick(()=>{
                    this.$refs.form.clearValidate()
                });
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            // 编辑
            showEdit(row){
                this.request({
                    url: '/bsnl-activity/activity/details',
                    //url: '/activity/details',
                    method: 'get',
                    params: {
                        id: row.id
                    }
                }).then(({data}) => {

                    if(data.type===4){
                        data.discount = data.discount ? data.discount : '';
                    }
                    else if(data.type===5){
                        data.full = data.full ? data.full : '';
                        data.price = data.price ? data.price : '';
                    }
                    else if(data.type===6){
                        data.tempActName = JSON.parse(data.actName);
                    }
                    this.formData = {
                        ...data,
                        timeRange: [data.startTime, data.stopTime]
                    };
                    this.$nextTick(()=>{
                        this.$refs.form.clearValidate()
                    });
                    this.showEditPop = true;
                    this.btnDisabled = false;
                }).catch(err => {
                    console.log(err);
                });
            },
            save(){
                this.$refs.form.validate(valid => {
                    if (!valid) {
                        return false;
                    }
                    let url = this.formData.id ? '/bsnl-activity/activity/update' : '/bsnl-activity/activity/create';
                    //let url = this.formData.id ? '/activity/update' : '/activity/create';
                    this.formData.startTime = this.formatDate(this.formData.timeRange[0], 'yyyy-MM-dd hh:mm:ss');
                    this.formData.stopTime = this.formatDate(this.formData.timeRange[1], 'yyyy-MM-dd hh:mm:ss');
                    this.formData.actName = JSON.stringify(this.formData.tempActName);
                    this.btnLoading = true;
                    this.request({
                        url,
                        method: 'post',
                        data: this.formData
                    }).then(() => {
                        this.btnLoading = false;
                        this.showEditPop = false;
                        this.$message.success('保存成功');
                        this.getList();
                    }).catch(err => {
                        this.btnLoading = false;
                    });
                });
            }
        }
    }
</script>
<style lang="scss">
    .line{
        color: transparent;
    }
    .banner-container{
        .avatar-uploader .el-upload{
            width: 120px;
            height: 120px;
            line-height: 118px;
        }
    }
    .el-row{
        margin-bottom: 12px;
    }
</style>
